from ..common.ui.PageElement import PageElement


class MulitSelect(PageElement):

    def getValue(self):
        self.wait_element_presence()
        script = "return $(arguments[0]).multiselect('value')"
        values = self._execute_script(script, self._get_web_element())
        if not values:
            return []
        strValues = [str(i) for i in values]
        textValues = self.__getTextValueFields__()
        result = []

        for textValue in textValues:
            if textValue[1] in strValues:
                result.append(textValue[0])
        return result

    def setValue(self, *values):
        self.wait_element_presence()
        textValueTuple = self.__getTextValueFields__()
        selectList = [];
        for textvalue in textValueTuple:
            if (textvalue[0] in values):
                selectList.append(textvalue[1])
        script = "$(arguments[0]).multiselect('value',['" + '\',\''.join(selectList) + "'])"
        self._execute_script(script, self._get_web_element())

    def clear(self):
        pass

    def __get_datasource__(self):
        script = "return $(arguments[0]).multiselect('option','dataSource')"
        return self._execute_script(script, self._get_web_element())

    def __getValueFields__(self):
        script = "var list = '';$(arguments[0]).children('option').each(function(index, time){(list+=$(this).attr('value') +',')}); return list"
        values = self._execute_script(script, self._get_web_element())
        valueList = values.split(',')
        valueList.remove('')
        return valueList

    def __getTextFields__(self):
        script = "var list = '';$(arguments[0]).children('option').each(function(index, time){(list+=$(this).text() +',')}); return list"
        texts = self._execute_script(script, self._get_web_element())
        textList = texts.split(',')
        textList.remove('')
        return textList

    def __getTextValueFields__(self):
        dataSource = self.__get_datasource__()
        if not dataSource:
            textFieds = self.__getTextFields__()
            valueFieds = self.__getValueFields__()
            return list(zip(textFieds, valueFieds))
        else:
            script = "return $(arguments[0]).multiselect('option','dataTextField')"
            textField = self._execute_script(script, self._get_web_element())
            script = "return $(arguments[0]).multiselect('option','dataValueField')"
            valueField = self._execute_script(script, self._get_web_element())
            result = [];
            for data in dataSource:
                result.append((str(data[textField]), str(data[valueField])))
            return result

    def get_identification(self):
        identification = {'data-ui-role': ['multiselect']}
        return identification